<?php
class UserIdentity extends CUserIdentity
{
	private $_id;
	
	public function authenticate()
    {
        $record = User::model()->findByAttributes(array('login'=>$this->username));
        if (null === $record) {
            $this->errorCode = self::ERROR_USERNAME_INVALID;
		} else if ($record->password !== self::encodePassword($this->password)) {
            $this->errorCode = self::ERROR_PASSWORD_INVALID;
		} else {
            $this->_id = $record->id;
			$this->setState('model', $record);
            $this->errorCode = self::ERROR_NONE;
        }
		$this->setErrorMessage();
        return !$this->errorCode;
    }

	public static function encodePassword($password)
	{
		return md5($password);
	}

	public function getId()
    {
        return $this->_id;
    }

	/**
	 * @return string
	 */
	private function setErrorMessage()
	{
		$messages = array(
			self::ERROR_NONE => '',
			self::ERROR_USERNAME_INVALID => 'Учетная запись не найдена',
			self::ERROR_PASSWORD_INVALID => 'Неправильный пароль',
			self::ERROR_UNKNOWN_IDENTITY => 'Учетная запись не найдена',
		);
		if (isset($messages[$this->errorCode])) {
			$this->errorMessage = $messages[$this->errorCode];
		}
	}

	
}